{% extends '__base__.html' %}

{% block title %}日志{% endblock %}
{% block beforehead %}
<script src="https://unpkg.com/vue@next"></script>
{% endblock %}
{% block content %}

<!-- Content Header (Page header) -->

<section class="content-header">
    <h1>
        Records
        <small>Records panel</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Records</li>
    </ol>
</section>

<div class="container">
    <div class="row">
        <div class="col" id="main">
            <h1>Index</h1>
        </div>
    </div>
</div>

{% endblock %}

{% block beforebody %}
<script>
    let isJSON = function (str){
        if (str.length <= 0) return false
        if (typeof str !== 'string') return false
        /*
        return /^[\],:{}\s]*$/.test(str.replace(/\\["\\\/bfnrtu]/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d (?:\.\d*)?(?:[eE][\-]?\d )?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[) /g, ''))
        */
        /*
        console.log(1, str.replace(/\\["\\\/bfnrtu]/g, '@'))
        console.log(2, str.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d(?:\.\d*)?(?:[eE][\-]?\d)?/g, ''))
        console.log(3, str.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d(?:\.\d*)?(?:[eE][\-]?\d)?/g, '').replace(/(?:^|:|,)(?:\s*\[) /g, ''))
        */
        str = str.replace(/\\["\\\/bfnrtu]/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d(?:\.\d*)?(?:[eE][\-]?\d)?/g, '').
            replace(/(?:^|:|,)(?:\s*\[) /g, '')
        // console.log(str.match(/^[\[\{].*[\}\]]$/))
        return /^[\[\{].*[\}\]]$/.test(str)
    }
    let showrs = {
        // data返回值是暴露的属性
        data() {
            return {
                // path: ['/root'],
                items: [],
                page: {'total': 0, 'pages': 1, 'index': 1, 'size': 12},
                pagesize: 1
            }
        },
        props: ['index'],
        methods: {
        },
        delimiters: ['+{', '}'],
        template: `
            <div class="row">
                <div class="col-md-10 accordion" id="accordionRecord">
                    <div class="row text-center">
                        <div class="col-2">访问IP</div>
                        <div class="col-5">请求</div>
                        <div class="col-2">状态</div>
                        <div class="col-3">时间</div>
                    </div>
                    <div v-for="item in items" class="card">
                        <div class="card-header user-select-none" :id="'heading' + item.id">
                            <div class="mb-0">
                                <div class="row text-nowrap" type="button" data-toggle="collapse" :data-target="'#collapse' + item.id" aria-expanded="true" :aria-controls="'collapse' + item.id">
                                    <div class="col-2 text-truncate" data-toggle="tooltip" data-placement="top" :title="item.remote">+{item.remote}</div>
                                    <div class="col-5 border-left text-truncate" data-toggle="tooltip" data-placement="top" :title="item.reqline">+{item.reqline}</div>
                                    <div class="col-2 border-left" data-toggle="tooltip" data-placement="top" :title="item.status">+{item.status}</div>
                                    <div class="col-3 border-left text-truncate" data-toggle="tooltip" data-placement="top" :title="item.created_at">+{item.created_at}</div>
                                </div>
                            </div>
                        </div>
                        <div :id="'collapse' + item.id" class="collapse" :aria-labelledby="'heading' + item.id" data-parent="#accordionRecord">
                            <textarea class="card-body" style="background-color: rgba(251, 241, 227, 0.95);width: 100%;" readonly rows='10' :value='JSON.stringify(this.formatItem(item), null, "\t")'></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div id="page" class="row user-select-none" style="cursor: pointer">
                <nav class="col-6 offset-4" aria-label="Page navigation example">
                    <ul class="pagination">
                        <li class="page-item" :class="{disabled: page.index == 1}">
                            <a class="page-link"
                                @click="loadItems(page.index - 1)"
                                aria-label="Previous">
                                <span aria-hidden="true">«</span>
                            </a>
                        </li>
                        <li class="page-item" v-for="index in range" :class="{disabled: index==page.index}">
                            <a class="page-link" @click="loadItems(index)"> +{index}</a>
                        </li>
                        <li class="page-item" :class="{disabled: page.index == page.pages}">
                            <a class="page-link"
                                @click="loadItems(page.index + 1)"
                                aria-label="Next">
                                <span aria-hidden="true">»</span>
                            </a>
                        </li>
                        <li class="page-item ">
                            <input @keyup.enter="loadItems($event.currentTarget.value)" class="page-link" style="width:50px">
                        </li>
                        <li class="page-item disabled">
                            <input class="page-link text-center" style="width:70px" :value="page.index + '/' + page.pages">
                        </li>
                        <li class="page-item">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <div class="input-group-text">每页: </div>
                                </div>
                                <input type="number" min="1" max="100" class="form-control" v-model="pagesize">
                            </div>
                        </li>
                    </ul>
                </nav>
            </div>
            `,
        mounted() {
            let page = localStorage.getItem('records.page')
            if (page != null && page != 'null' && page != undefined && page != 'undefined') {
                this.page = JSON.parse(page)
            }
            this.loadItems(1)
            this.pagesize = this.page.size
        },
        watch: {
            pagesize(newVal, oldVal) {
                console.log(newVal, oldVal)
                this.page.size = this.pagesize
                localStorage.setItem('records.page', JSON.stringify(this.page))
            }
        },
        updated() {
        },
        methods: {
            formatItem(item) {
                let result = {}
                for (key in item) {
                    // console.log(item[key])
                    result[key] = isJSON(item[key])?this.formatItem(JSON.parse(item[key])):item[key]
                    // result[key] = item[key]
                }
                return result
            },
            loadItems(index, pagesize=12) {
                if (index > this.page.pages) return
                axios.get('/records/items?index=' + index + '&pagesize=' + this.page.size)
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                    this.page = data['msg']['page'] ? data['msg']['page'] : this.page
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
        computed: {
            pageSize() {
                return this.page.size
            },
            range() {
                range = []
                if (this.page.pages <= 5) {
                    for (let i = 1; i <= this.page.pages; ++i) {
                        range.push(i)
                    }
                } else {
                    if (this.page.index <= 3) {
                        for (let i = 1; i <= 5; ++i) {
                            range.push(i)
                        }
                    }
                    if (this.page.index > 3 && this.page.index < this.page.pages - 2) {
                        for (let i = this.page.index - 2; i <= this.page.index + 2; ++i) {
                            range.push(i)
                        }
                    }
                    if (this.page.index >= this.page.pages - 2) {
                        for (let i = this.page.pages - 4; i <= this.page.pages; ++i) {
                            range.push(i)
                        }
                    }
                }
                if (range.length === 0) range = [1]
                return range
                // console.log(this.range)
            }
        }
    }
    const app = Vue.createApp(showrs)
    // mount方法返回根组件实例
    const vm = app.mount('#main')
</script>
{% endblock %}